'use strict';

const { Service } = require('egg');
class UserService extends Service {
  async selectAll() { // 查询全部用户
    const data = await this.app.model.User.find({}); // 执行mongoose的查询语句
    return data;
  }
  // 用户登录的方法
  async login(userObj) {
    const data = await this.app.model.User.find({ userName: userObj.userName, userPwd: userObj.userPwd });
    if (data.length === 0) {
      // ctx.body = { coed: 501, msg: '缺少必填项;密码不能为空' };
      return { code: 501, msg: '用户名或密码错误' };
    } else {
      return { code: 200, msg: data[0] };
      // return data;
    }
  }
  // 用户注册的方法
  async register(userObj) {
    const allUser = await this.app.model.User.find({ userName: userObj.userName });
    if (allUser.length === 0) {
      const model = new this.app.model.User(userObj);
      await model.save();
      return { code: 200, data: model };
    } else {
      return { code: 501, msg: '用户已存在' };
      // ctx.body = { coed: 501, msg: '用户已存在,请更换用户名' };
    }
  }
  // 用户删除的方法
  async deleteUser(userName) {
    const data = await this.app.model.User.remove({ userName });
    if (data.n >= 1) {
      return { code: 200, data };
    } else {
      return { code: 501, msg: '删除失败' };
    }
  }
  // 用户修改全部的个人信息(管理员负责调用,不可以修改用户userName和用户密码)
  async updateByAdmin(newUserObj) {
    const data = await this.app.model.User.update({ userName: newUserObj.userName }, { $set: { nickname: newUserObj.nickname, userPortrait: newUserObj.userPortrait, realName: newUserObj.realName, userSex: newUserObj.userSex, borrowNumber: newUserObj.borrowNumber, borrowHistory: newUserObj.borrowHistory } });
    if (data.n >= 1) {
      return { code: 200, data };
    } else {
      return { code: 501, msg: '修改失败' };
    }
  }
  // 用户修改全部的个人信息(用户负责调用,不可以修改用户userName和借阅信息和借书数量)
  async updateByUser(newUserObj) {
    const data = await this.app.model.User.update({ userName: newUserObj.userName }, { $set: { nickname: newUserObj.nickname, userPortrait: newUserObj.userPortrait, realName: newUserObj.realName, userSex: newUserObj.userSex, userPwd: newUserObj.userPwd } });
    if (data.n >= 1) {
      return { code: 200, data };
    } else {
      return { code: 501, msg: '修改失败!!!' };
    }
  }
  // 根据用户名称查找用户信息
  async findByUserName(userName) {
    const data = await this.app.model.User.find({ userName }); // 执行mongoose的查询语句
    if (data.length === 0) {
      return { code: 501, msg: '查找失败' };
    } else {
      return data;
    }
  }
  // 分页查询用户信息
  async limitUser(pagenumber, limit) {
    const number = parseInt((pagenumber - 1) * limit);
    const data = await this.app.model.User.find({}).skip(number).limit(parseInt(limit)).sort({});
    if (data.length !== 0) {
      return data;
    } else {
      return { code: 201, data, msg: '数据显示完毕' };
    }
  }
}

module.exports = UserService;
